package org.example.k8s_cloudplatform.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import org.example.k8s_cloudplatform.scheduler.ExpirationScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EmailVerifyUtil {
    private final static String HOST = "smtp.qq.com";
    private final static String SENDER = "rollercoaster_k8s@foxmail.com";
    private final static String KEY = "lhgeelskrzpfdbfa";
    private static final Logger logger = LoggerFactory.getLogger(ExpirationScheduler.class);

    /**
     * 立即发送邮件(调用此方法以避免发送邮件时阻塞)，使用线程池异步发送
     * 此方法加速以报错信息减少为代价，且无法保证邮件发送成功
     *
     * @param recipient 邮件接收者
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public static void sendMailImmediately(String recipient, String subject, String content) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            try {
                sendMail(recipient, subject, content);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
                logger.error("目标地址为" + recipient + "的邮件发送失败,内容为"+content);
            }
        });
        executor.shutdown();
    }

    public static void sendMail(String recipient, String subject, String content) throws Exception {
        Properties properties = new Properties();
        properties.setProperty("mail.host", HOST);
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");


        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SENDER, KEY);
            }
        });

        Transport transport = session.getTransport();
        transport.connect(HOST, SENDER, KEY);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(SENDER));
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        mimeMessage.setSubject(subject);
        mimeMessage.setContent(content, "text/html;charset=UTF-8");

        try {
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            transport.close();
        }
    }
}
